const express = require('express')
const validUrl = require('valid-url')
const shortid = require('shortid')
const router = express.Router()

const UrlModal = require('../models/Url.js')
const config = require('config')

// 手动阻塞 ms
async function sleep(time) {
    return new Promise((resolve) => {
        let timer = setTimeout(() => {
            resolve()
            clearTimeout(timer)
        }, time)
    })
}

// @route POST api/url/shorten
// @desc 创建短链接
router.post('/shorten', async (req, res) => {
    await sleep(2000)
    // 1. 获取长连接
    const { longURL } = req.body
    // 2. 验证长连接合法性
    if (!validUrl.isUri(longURL)) {
        return res.status(401).json('无效的Url！')
    }

    // 3. 用url code 生成短链接
    const urlCode = shortid.generate()
    const shortUrl = config.get('baseUrl') + urlCode

    try {
        // 5. 存入数据库 判断longURL是否已在数据库中
        let url = await UrlModal.findOne({ longUrl: longURL }).exec()
        if (url) {
            return res.json(url)
        } else {
            url = new UrlModal({
                longUrl: longURL,
                urlCode,
                shortUrl,
                data: new Date()
            })
            url.save()
            console.log('save url')
            res.json(url)
        }
    } catch (err) {
        console.error(err)
        res.status(500).json('Server error: ' + err.message)
    }
})

module.exports = router